<template>
  <div class="search">
    <van-nav-bar
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      fixed
      placeholder
      right-text="搜索"
      @click-right="onSearch"
    >
      <template #title>
        <van-search shape="round" placeholder="请输入搜索关键词" @search="onSearch" v-model="searchValue" />
      </template>
    </van-nav-bar>
    <item2-list ref="item2List" @click="clickItem" />
  </div>
</template>

<script>
import Item2List from "@/components/item/Item2List.vue";
import { NavBar, Search } from "vant";
export default {
  name: "Search",
  components: {
    Item2List,
    [NavBar.name]: NavBar,
    [Search.name]: Search
  },
  data() {
    return {
      searchValue: ""
    };
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.searchValue = to.params.q;
      if (vm.searchValue) {
        vm.$ajax
          .post("/commodity/v1/search", { q: vm.searchValue })
          .then(function(r) {
            vm.$refs.item2List.replace(r.data.data);
          });
      }
    });
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1);
    },
    onSearch() {
      let vm = this;
      vm.$ajax
        .post("/commodity/v1/search", { q: vm.searchValue })
        .then(function(r) {
          vm.$refs.item2List.replace(r.data.data);
        });
    },
    clickItem(token) {
      this.$router.push({
        path: "/itemInfo",
        query: { token }
      });
    }
  }
};
</script>

<style scoped>
.search {
  background-color: #eee;
  padding: 10px;
}

.search .van-search {
  padding: 6px 0;
}

.search .van-card {
  margin: 10px;
  border-radius: 10px;
  background-color: white;
}
</style>